<template>
  <el-dialog :append-to-body="true" :close-on-click-modal="false" :before-close="cancel" :visible.sync="dialog" :title="isAdd ? '新增' : '编辑'" width="50%">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
      <el-form-item label="排序">
        <el-input v-model="form.sort" style="width: 300px;" />
      </el-form-item>

      <el-form-item label="图片落地页">
        <el-radio v-for="item in dict.pages_dict" :key="item.id" v-model="form.path" :label="item.value">{{ item.label }}</el-radio>
        <div>{{ form.path }}<el-input v-if="form.path && form.path.lastIndexOf('=') >= 0" v-model="form.queryVal" style="width: 80px;" placeholder="参数" /></div>
      </el-form-item>

      <el-form-item label="图片">
        <MaterialList v-model="form.imageArr" style="width: 300px" type="image" :num="1" :width="343" :height="180" />
        <span>建议图片大小(686*360)</span>
      </el-form-item>

      <el-form-item label="关联商品1" prop="nameList">
        <div><el-button icon="el-icon-s-grid" @click="openGoods('goodsList')">选择商品</el-button></div>
        <div class="goodsbox">
          <el-card v-for="( goods, index ) in form.goodsList" :key="goods.id" :body-style="{ padding: '0px' }" class="goods">
            <el-image :src="goods.image" class="goodsImage" fit="fill" />
            <div style="padding: 10px;">
              <div class="view-text">{{ goods.storeName }}</div>
              <div class="bottom clearfix">
                <el-button type="text" class="button" icon="el-icon-back" @click="sortUp(index,1)" />
                <el-button type="text" class="button" icon="el-icon-right" @click="sortDown(index,1)" />
                <el-button type="text" class="button" icon="el-icon-close" @click="handleCloseTag(index,1)" />
              </div>
            </div>
          </el-card>
        </div>
      </el-form-item>

      <el-form-item label="关联商品2" prop="nameList">
        <div><el-button icon="el-icon-s-grid" @click="openGoods('goodsList2')">选择商品</el-button></div>
        <div class="goodsbox">
          <el-card v-for="( goods, index ) in form.goodsList2" :key="goods.id" :body-style="{ padding: '0px' }" class="goods">
            <el-image :src="goods.image" class="goodsImage" fit="fill" />
            <div style="padding: 10px;">
              <div class="view-text">{{ goods.storeName }}</div>
              <div class="bottom clearfix">
                <el-button type="text" class="button" icon="el-icon-back" @click="sortUp(index,2)" />
                <el-button type="text" class="button" icon="el-icon-right" @click="sortDown(index,2)" />
                <el-button type="text" class="button" icon="el-icon-close" @click="handleCloseTag(index,2)" />
              </div>
            </div>
          </el-card>
        </div>
      </el-form-item>

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>

    <choosegoods v-if="showGoods" :is-sigle="false" @handleclose="cancelGoods" @confirmGoods="confirmGoods" />

  </el-dialog>
</template>

<script>
import { add, edit } from '@/api/yxSystemGroupData'
import { getDetail } from '@/api/yxStoreProduct'
import { duplicate } from '@/utils/index'
import picUpload from '@/components/pic-upload'
import MaterialList from '@/components/material'
import choosegoods from '../../components/ChooseGoods'

export default {
  // eslint-disable-next-line vue/no-unused-components
  components: { picUpload, MaterialList, choosegoods },
  dicts: ['pages_dict'],
  props: {
    isAdd: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      loading: false, dialog: false,
      form: {
        id: '',
        groupName: 'cate_product',
        wxapp_url: '',
        pic: '',
        imageArr: [],
        sort: '',
        status: '',
        path: '/pages/cate/goods?cateId=',
        queryVal: '',
        goodsList: [],
        goodsList2: []
      },
      curListName: 'goodsList',
      rules: {
      },
      showGoods: false
    }
  },
  watch: {
    'form.imageArr': function(val) {
      if (val) {
        this.form.pic = val.join(',')
      }
    }
  },
  methods: {
    duplicate,
    sortUp(index, type) {
      if (type === 1) {
        if (index !== 0) {
          this.form.goodsList[index] = this.form.goodsList.splice(index - 1, 1, this.form.goodsList[index])[0]
        } else {
          this.form.goodsList.push(this.form.goodsList.shift())
        }
      } else {
        if (index !== 0) {
          this.form.goodsList2[index] = this.form.goodsList2.splice(index - 1, 1, this.form.goodsList2[index])[0]
        } else {
          this.form.goodsList2.push(this.form.goodsList2.shift())
        }
      }
    },
    sortDown(index, type) {
      if (type === 1) {
        if (index !== this.form.goodsList.length - 1) {
          this.form.goodsList[index] = this.form.goodsList.splice(index + 1, 1, this.form.goodsList[index])[0]
        } else {
          this.form.goodsList.unshift(this.form.goodsList.splice(index, 1)[0])
        }
      } else {
        if (index !== this.form.goodsList2.length - 1) {
          this.form.goodsList2[index] = this.form.goodsList2.splice(index + 1, 1, this.form.goodsList2[index])[0]
        } else {
          this.form.goodsList2.unshift(this.form.goodsList2.splice(index, 1)[0])
        }
      }
    },
    handleCloseTag(index, type) {
      console.log('handleCloseTag===>', index)
      if (type === 1) {
        this.form.goodsList.splice(index, 1)
      } else {
        this.form.goodsList2.splice(index, 1)
      }
    },
    cancelGoods() {
      this.showGoods = false
    },
    openGoods(val) {
      this.curListName = val
      this.showGoods = true
    },
    confirmGoods(goodsList = []) {
      this.showGoods = !this.showGoods
      if (goodsList && goodsList.length > 0) {
        this.form.image = []
        if (this.form[this.curListName].length === 0) {
          this.form[this.curListName] = goodsList
        } else {
          const newList = new Set([...goodsList, ...this.form[this.curListName]])
          this.form[this.curListName] = this.duplicate(Array.from(newList), 'id')
        }
      }
    },
    loadProduct() {
      const id = this.form.queryVal
      const that = this
      getDetail(id).then(res => {
        that.form.goodsName = res.storeName
        that.form.goodsPrice = res.price
        that.form.goodsSourcePrice = res.otPrice
        this.form.imageArr.push(res.image)
      })
    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.loading = true
      if (this.isAdd) {
        this.doAdd()
      } else this.doEdit()
    },
    changeList() {
      if (this.form.goodsList.length > 0) {
        const newGoodsList = []
        this.form.goodsList.forEach((goods, index) => {
          const _goods = {
            id: goods.id,
            sort: index,
            image: goods.image,
            storeName: goods.storeName,
            price: goods.price,
            otPrice: goods.otPrice
          }
          newGoodsList.push(_goods)
        })
        this.form.goodsList = newGoodsList
      }
      if (this.form.goodsList2.length > 0) {
        const newGoodsList = []
        this.form.goodsList2.forEach((goods, index) => {
          const _goods = {
            id: goods.id,
            sort: index,
            image: goods.image,
            storeName: goods.storeName,
            price: goods.price,
            otPrice: goods.otPrice
          }
          newGoodsList.push(_goods)
        })
        this.form.goodsList2 = newGoodsList
      }
    },
    doAdd() {
      this.form.wxapp_url = this.form.path
      if (this.form.queryVal && this.form.queryVal !== undefined) {
        this.form.wxapp_url = this.form.path + this.form.queryVal
      }
      this.changeList()
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    doEdit() {
      this.form.wxapp_url = this.form.path
      if (this.form.queryVal && this.form.queryVal !== undefined) {
        this.form.wxapp_url = this.form.path + this.form.queryVal
      }
      this.changeList()
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.form = {
        id: '',
        groupName: 'cate_product',
        imageArr: [],
        value: '',
        addTime: '',
        sort: 0,
        status: ''
      }
    }
  }
}
</script>

<style scoped>
.goodsbox{
  width: 100%;
  /* height: 200px; */
  /* border: 1px solid red; */
  overflow: auto;
  position: relative;
  white-space:nowrap;
}
.goods{
  margin: 20px 20px 20px 0px;
  display:  inline-block;;
  width: 120px;
  height: 210px;
   white-space: normal;
  /* border: 1px solid blue; */
  /* float: left; */
}

.view-text{
  /* border: 1px solid red; */
  max-height: 80px;;
  width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  font-size: 10px;
  line-height: 15px;
}

.goodsTags{
  margin-right: 10px;
}
.bottom {
    margin-top: 13px;
    line-height: 12px;
    display: flex;
}
.button {
  flex: 1;
  padding: 0;
  /* float: right; */
}
.goodsImage {
  width: 120px;
  height: 120px;
}
.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}
.clearfix:after {
    clear: both
}
.card-body{
  width: 120px;
  /* border:1px solid red; */
  /* padding: 0px; */
  margin: 20px 20px 20px 0px;
}
</style>
